from flask import Flask, request, jsonify

app = Flask(__name__)

# 简单的Bearer Token
VALID_TOKEN = "my-secret-token"

def check_bearer_token():
    """检查Bearer Token"""
    auth_header = request.headers.get('Authorization')
    if not auth_header:
        return False
    
    # 检查格式: "Bearer <token>"
    parts = auth_header.split()
    if len(parts) != 2 or parts[0].lower() != 'bearer':
        return False
    
    token = parts[1]
    return token == VALID_TOKEN

@app.route('/add', methods=['POST'])
def add():
    # 检查Bearer Token
    if not check_bearer_token():
        return jsonify({"error": "未授权"}), 401
    
    data = request.get_json()
    if not data or 'a' not in data or 'b' not in data:
        return jsonify({"error": "参数错误"}), 400
    
    a = data['a']
    b = data['b']
    result = a + b
    with open('result.txt', 'w') as f:
        f.write(f"{a} + {b} = {result}\n")
    return jsonify({"result": result})

if __name__ == '__main__':
    app.run(debug=True, host='192.168.0.3', port=5000)
